package com.xxin.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.io.Resources;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Optional;
import java.util.Properties;

/**
 * @author 小欣
 * @version 1.0
 * @since 1.8
 */
public class AuthenticationFilter implements Filter {
	
	/**
	 * 排除的路径
	 */
	@Value("${authentication.excludeUrl}")
	private String excludeUrl;
	
	{
		try {
			Properties prop = new Properties();
			prop.load(Resources.getResourceAsStream("application.properties"));
			excludeUrl = prop.getProperty("authentication.excludeUrl");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String servletPath = req.getServletPath();
		for (String s : excludeUrl.split(",")) {
			if(s.trim().equals(servletPath)){
				//不拦截的请求
				chain.doFilter(request,response);
				return;
			}
		}
		//获取session
		HttpSession session = req.getSession();
		Object currentUser = session.getAttribute("currentUser");
		Optional.ofNullable(currentUser).ifPresentOrElse(object -> {
			try {
				//放行请求
				chain.doFilter(request,response);
			} catch (IOException | ServletException e) {
				e.printStackTrace();
			}
		},() -> {
			try {
				//重定向到登录页面
				res.sendRedirect("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}
}
